import { createRouter, createWebHistory } from 'vue-router'
import HomeView from '@/views/HomeView.vue'
import LoginView from '@/views/LoginView.vue'
import OrderList from '@/views/OrderList.vue'
import CinemaView from '@/views/CinemaView.vue'
import TetrisView from '@/views/TetrisView.vue'
import ProfileView from '@/views/ProfileView.vue'
import RPGGameView from '@/views/RPGGameView.vue'
import PaymentView from '@/views/PaymentView.vue'

const routes = [
  {
    path: '/',
    name: 'home',
    component: HomeView,
    meta: { requiresAuth: false }
  },
  {
    path: '/login',
    name: 'login',
    component: LoginView,
    meta: { requiresAuth: false }
  },
  {
    path: '/films',
    name: 'films',
    component: () => import('@/views/Films.vue'),
    meta: { requiresAuth: false }
  },
  {
    path: '/cinema',
    name: 'cinema',
    component: CinemaView,
    meta: { requiresAuth: false }
  },
  {
    path: '/movieDetail/:id',
    name: 'movie-detail',
    component: () => import('@/views/MovieDetail.vue'),
    meta: { requiresAuth: false }
  },
  {
    path: '/movie/:id/cinema/:cinemaId/buy',
    name: 'movie-buy',
    component: () => import('@/views/MovieBuyView.vue'),
    meta: { requiresAuth: true }
  },
  {
    path: '/seat-selection',
    name: 'seat-selection',
    component: () => import('@/views/SeatView.vue')
  },
  {
    path: '/cinema/:id',
    name: 'cinema-detail',
    component: () => import('@/views/CinemaDetailView.vue'),
    meta: { requiresAuth: false }
  },
  {
    path: '/payment',
    name: 'payment',
    component: PaymentView,
    meta: { requiresAuth: true }
  },
  {
    path: '/orders',
    name: 'orders',
    component: OrderList,
    meta: { requiresAuth: false }
  },
  {
    path: '/cinemas',
    name: 'cinemas',
    component: CinemaView,
    meta: { requiresAuth: false }
  },
  {
  path: '/profile',
  name: 'profile',
  component: ProfileView,
  meta: {
    requiresAuth: true // 可选：添加需要登录的元信息
  }
},
  {
    path: '/tetris',
    name: 'tetris',
    component: TetrisView
  },
  {
    path: '/rpg-game',
    name: 'rpg-game',
    component: RPGGameView
  }
]

const router = createRouter({
  history: createWebHistory(process.env.BASE_URL),
  routes,
  scrollBehavior(to, from, savedPosition) {
    return savedPosition || { top: 0 }
  }
})

// 全局前置守卫
router.beforeEach((to, from, next) => {
  // 添加页面加载状态
  document.body.classList.add('page-loading')

  // 检查是否需要登录
  if (to.meta.requiresAuth) {
    const userData = localStorage.getItem('user')
    if (!userData) {
      next('/login')
      return
    }
  }


  // 检查是否需要登录认证
  if (to.meta.requiresAuth) {
    const token = localStorage.getItem('token')
    if (!token) {
      next({
        path: '/login',
        query: { redirect: to.fullPath }
      })
      return
    }
  }
  next()
})

// 全局后置守卫
router.afterEach(() => {
  // 延迟移除加载状态,避免闪烁
  setTimeout(() => {
    document.body.classList.remove('page-loading')
  }, 100)
})

export default router
